#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <string.h>
#include <unistd.h>
#include <signal.h>
#include <wait.h>
#include <errno.h>

#define MYPORT 10001
#define MAXLINE 1024

//使用fork 处理多个客户请求
void sig_chld(int signo){
    pid_t pid;
    while((pid = waitpid(-1, NULL, WNOHANG)) > 0){
        printf("child %d terminated!\n", pid);
    }
    return;
}

int main(){
    int listen_fd = socket(AF_INET, SOCK_STREAM, 0);
    if(listen_fd < 0){
        perror("socket()");
        return 1;
    }
    socklen_t cli_len;
    struct sockaddr_in cliaddr;
    struct sockaddr_in seraddr;
    memset(&seraddr, 0, sizeof(seraddr));
    seraddr.sin_family = AF_INET;
    seraddr.sin_addr.s_addr = htonl(INADDR_ANY);
    seraddr.sin_port = htons(MYPORT);

    signal(SIGCHLD, sig_chld);

    if(bind(listen_fd, (struct sockaddr*)&seraddr, sizeof(seraddr)) < 0){
        perror("bind()");
        return 1;
    }
    
    if(listen(listen_fd,3) < 0){
        perror("listen()");
        return 1;
    }
    int con_fd;
    while(1){
        cli_len = sizeof(cliaddr);
        if((con_fd = accept(listen_fd, (struct sockaddr*)&cliaddr, &cli_len)) < 0){
            if(errno == EINTR){
                continue;
            }
            perror("accept()");
            return 1;
        }
        char buf[256];
        printf("accept from %s, port %d\n", inet_ntop(AF_INET, &cliaddr.sin_addr, buf, cli_len), ntohs(cliaddr.sin_port));
        char buffer[MAXLINE];
        pid_t pid;
        if((pid = fork()) == -1){
            perror("fork()");
            return -1;
        }
        else if(pid == 0){
            close(listen_fd);
            int n;
            while((n = read(con_fd, buffer, MAXLINE)) > 0){
                //printf("%s", buffer);
                write(con_fd, buffer, n);
            }
            close(con_fd);
            exit(0);
        }
        close(con_fd);
    }
    return 0;
}